package com.lawyers.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lawyers.common.ComentarioVO;
import com.lawyers.common.UserVO;
import com.lawyers.database.DBAcciones;
import com.lawyers.form.MisDemandasForm;

public class MisDemandasAction extends Action {

	private static Logger logger = Logger.getLogger(MisDemandasAction.class);
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		logger.info("");
		
		MisDemandasForm misDemandasForm = (MisDemandasForm) form;
		String accion = misDemandasForm.getAccion();
		UserVO user = (UserVO) request.getSession().getAttribute("USUARIO");
		String idDemanda = "";
		if(misDemandasForm.getIdDemanda() == null || "".equals(misDemandasForm.getIdDemanda())){
			idDemanda = request.getAttribute("idDemanda").toString();
			misDemandasForm.setIdDemanda(idDemanda);
		}

		if (user == null)
			return mapping.findForward("login");

		if ("insertar".equalsIgnoreCase(accion)) {
			try {
				ComentarioVO comentario = new ComentarioVO();
				comentario.setFecha(misDemandasForm.getFecha());
				comentario.setObservaciones(misDemandasForm.getObservaciones());
				comentario.setIdDocumento(Integer.parseInt(misDemandasForm.getIdDemanda()));
				DBAcciones.insertarComentario(comentario);
				misDemandasForm.setDemandas(DBAcciones.getDemanda(Integer.parseInt(misDemandasForm.getIdDemanda())));
				misDemandasForm.setComentarios(DBAcciones.getComentarios(Integer.parseInt(misDemandasForm.getIdDemanda())));
				misDemandasForm.reset();
			} catch (Exception e) {
				logger.error("No vino el idDemanda seteado.");
				response.sendRedirect("ListarMisDemandas.do?accion=display");
				return null;
			}
			return mapping.findForward("display");
		}else{
			int idDemand = 0;
			try{idDemand = Integer.parseInt(misDemandasForm.getIdDemanda());}catch(Exception e){}
			List<ComentarioVO> comentarios = DBAcciones.getComentarios(idDemand);
			misDemandasForm.setComentarios(comentarios);
			misDemandasForm.setDemandas(DBAcciones.getDemanda(idDemand));
			return mapping.findForward("display");
		}
		
	}
	
}
